package com.qyer.search.model;

import static com.qyer.commons.utils.CommonUtils.cast2Int;
import static com.qyer.commons.utils.CommonUtils.cast2String;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.qyer.search.enums.KeyType;
import com.qyer.search.model.mutable.PreferKey;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * User: Z J Wu Date: 2016/01/07 Time: 13:12 Package: com.qyer.search.model
 */
public class User {

  public static final User UNKNOWN_USER = new User(0, "");

  @JsonProperty
  private int uid;

  @JsonProperty("unique_id")
  private String uniqueId;

  private User() {
  }

  private User(int uid, String uniqueId) {
    this.uid = uid;
    this.uniqueId = uniqueId;
  }

  public int getUid() {
    return uid;
  }

  public void setUid(int uid) {
    this.uid = uid;
  }

  public String getUniqueId() {
    return uniqueId;
  }

  public void setUniqueId(String uniqueId) {
    this.uniqueId = uniqueId;
  }

  public static User buildUser(HttpServletRequest request) {
    int uid = cast2Int(request.getParameter("uid"));
    String uniqueId = cast2String(request.getParameter("guid"));
    return (uid <= 0 && StringUtils.isBlank(uniqueId)) ? UNKNOWN_USER : new User(uid, uniqueId);
  }

  //add by tang
  //构造prefer key
  public PreferKey getKey(int channel){
    if(uid > 0)
      return new PreferKey(String.valueOf(uid), KeyType.UID);
    if(StringUtils.isNotEmpty(uniqueId))
      if( channel==1 ){
        return new PreferKey(uniqueId, KeyType.GUID);
      }else {
        return new PreferKey(uniqueId, KeyType.DEVICEID);
      }
    return null;
  }

}
